package cn.kgc.shiro;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;

public class ShiroAuthentication {

    public static void main(String[] args) {

        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        // IniRealm iniRealm = new IniRealm("classpath:user.ini");
        //  创建自定义realm对象  实现认证或授权的数据查询数据库
        CustomerRealm customerRealm = new CustomerRealm();
        // 创建凭证匹配器对象
        HashedCredentialsMatcher md5 = new HashedCredentialsMatcher("MD5");
        // 设置凭证匹配器 hash的次数
        md5.setHashIterations(10);

        customerRealm.setCredentialsMatcher(md5);
        defaultSecurityManager.setRealm(customerRealm);

        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("tom", "123456");
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            System.out.println("用户名错误");
        }catch (IncorrectCredentialsException e){
            System.out.println("密码错误");
        }

        boolean authenticated = subject.isAuthenticated();
        System.out.println("authenticated = " + authenticated);

    }
}
